from django.test import TestCase
from django.test.client import Client

class AssetsTest(TestCase):
    def setUp(self):
        self.client = Client()

    def test_service(self):
        self.client.login(username='sue', password='sue')
        print self.url
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        self.content = response.content

from django.http import HttpResponse, HttpResponseNotFound
from assets.util import get_services  
from django.shortcuts import render_to_response 
from django.template import RequestContext     

def tests(request):	
  services = get_services()
  services = [s for s in services if not 'django.views.static.serve' == s.module]
  return render_to_response('tests.html', {'services': services}, context_instance=RequestContext(request))

def test(request):	
  url = request.GET.get('url', None)
  if not url:
    return HttpResponseNotFound()
    
  services = get_services()
  
  services = [s for s in services if url == s.url]
  if len(services) != 1:
    return HttpResponseNotFound()
  service = services[0]
  if not service.has_arguments:
    from tests import AssetsTest
    from django.test.utils import setup_test_environment
    from unittest import TestResult
    from django.utils import simplejson

    setup_test_environment()
    t = AssetsTest('test_service')
    t.url = service.url.replace('^', '/').replace('$', '')
    r = TestResult()
    t.run(r)
    
    errors = simplejson.dumps([[str(y) for y in x] for x in r.errors + r.failures])
    if r.wasSuccessful():
      return HttpResponse(str(t.content), status=200) 
    else:
      return HttpResponse(errors, status=400) 
  return HttpResponse('Cant test', status=200) 
